﻿package com.sff.webservice {
	
	import com.sff.webservice.data.WSOperations;
	import com.sff.webservice.events.WebServiceEvent;
	
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	
	/**
	 * This class will create WebService object and load WebService Descriptor into operations property.
	 */
	public class WebService extends EventDispatcher {
		
		private var strURL			:String;
		private var arrQeue			:Array;
		private var arrOperations	:WSOperations;

		public function WebService(url:String) {
			strURL = url;			
			arrQeue = new Array();
		}

		public function loadWSDL():void {
			var ldr:URLLoader = new URLLoader();
			registerLoader(ldr);
			
			ldr.dataFormat = URLLoaderDataFormat.TEXT;
			ldr.load(new URLRequest(strURL));
		}
		
		private function registerLoader(ldr:URLLoader):void {
			ldr.addEventListener(Event.COMPLETE, onLoadDescriptorHandler);
			ldr.addEventListener(IOErrorEvent.IO_ERROR, onErrorDescriptorHandler);
			ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErrorDescriptorHandler);
		}
		
		private function unregisterLoader(ldr:URLLoader):void {
			ldr.removeEventListener(Event.COMPLETE, onLoadDescriptorHandler);
			ldr.removeEventListener(IOErrorEvent.IO_ERROR, onErrorDescriptorHandler);
			ldr.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErrorDescriptorHandler);				
		}
		
		private function onErrorDescriptorHandler(evt:IOErrorEvent):void {
			unregisterLoader(evt.currentTarget as URLLoader);			
			dispatchEvent(new WebServiceEvent(WebServiceEvent.WSDL_FAILED));
		}

		private function onSecurityErrorDescriptorHandler(evt:SecurityErrorEvent):void {
			unregisterLoader(evt.currentTarget as URLLoader);			
			dispatchEvent(new WebServiceEvent(WebServiceEvent.WSDL_FAILED));
		}
				
		private function onLoadDescriptorHandler(evt:Event):void {
			unregisterLoader(evt.currentTarget as URLLoader);	
			
			try {
				arrOperations = new WSOperations();
				arrOperations.parse(new XML(evt.currentTarget.data));
								
				dispatchEvent(new WebServiceEvent(WebServiceEvent.WSDL_RESULT));
				
			} catch (err:TypeError) {
				dispatchEvent(new WebServiceEvent(WebServiceEvent.WSDL_FAILED));
			}
		}
		
		public function get operations():WSOperations {
			return arrOperations;
		}
		
		public function get wsdlURL():String {
			return strURL;
		}
	}
}
